import axios from 'axios'


class HttpRequest {
    constructor(baseUrl) {
        this.baseUrl = baseUrl
        this.queue = {}
    }

    getInsideConfig() {
        const config = {
            baseURL: this.baseUrl,
            headers: {}
        }
        return config
    }

    destroy(url) {
        delete this.queue[url]
    }

    interceptors(instance, url) {
        // 添加请求拦截器 在请求或响应被 then 或 catch 处理前拦截它们。
        instance.interceptors.request.use(config => {
            this.queue[url] = true
            return config;
        }, error => {
            return Promise.reject(error)
        })

        // 添加响应拦截器
        instance.interceptors.response.use((res) => {
            // 对响应数据做点什么
            this.destroy(url)
            const {data, status} = res;
            return {data, status}
        }, (error) => {
            // 对响应错误做点什么
            this.destroy(url);
            let errorInfo = error.response
            if (!errorInfo) {
                const {request: {statusText, status}, config} = JSON.parse(JSON.stringify(error));
                errorInfo = {
                    statusText,
                    status,
                    request: {responseURL: config.url}
                }
            }
            return Promise.reject(error);
        });
    }

    request(options) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

export default HttpRequest
